#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h> 
#include <mqueue.h>

#include "config.h"
#include "ecriture_windows.h"


#define BUFFER_SIZE 256


// ------------------- SCRIPT INFO -------------------------------
// This thread creates a TCP Internet socket port 5001 that accept a client connexion.
// It's the client which connects to the socket.
// We will use this socket to send the client traces and dialogs, to the operator. 
//
// Running loop: we wait for msg from BAL_versEcriture, and relieve it to the operator
// by the socket.





// Used to formate data to be sent by socket to the operator.
// Converts an int into a string.
// The integer needed contains "size" decimals, so it completes with 0 when necessary
// (ex: i convert 456 with size = 5 -> result = "00456"
void parseStr(char * result, int size, int nb)
{
	char nombre[size+1];
	snprintf(nombre, size+1, "%d", nb);

	int completion = size - strlen(nombre);
	if(completion > 0)
	{
		char zeros[completion];
		strcpy(zeros,"0");
		if(completion > 1)
		{
			int i;
			for(i=0;i<completion-1;i++)
			{
				strcat(zeros,"0");
			}
		}
		strcpy(result, zeros);
		strcat(result, nombre);
	}
	else
	{
		strcpy(result, nombre);
	}
}


void *EcritureWindows()
{
	
// ------------------------------------------------------------------
// 			1. INITIALISATION				
// ------------------------------------------------------------------

	// -------------- LINUX APPLICATION INTERFACE --------------//

	mqd_t queue_versEcriture;
	int reading_size;
	MSG_versEcriture msg_versEcriture;

	// opening "BAL_versEcriture", READ only
	queue_versEcriture = mq_open(BAL_versEcriture, O_RDONLY);



	// ------------- NETWORK INTERFACE ------------------------//

	int listenfd = 0, connfd = 0;
	struct sockaddr_in serv_addr;

	listenfd = socket(AF_INET, SOCK_STREAM, 0); // socket INTERNET over TCP
	memset(&serv_addr, '0', sizeof(serv_addr)); // initialisation 

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(5001);  //set the port to 5001

	bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 

	listen(listenfd, 10);  //listen up to then client connecting

	connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); //accept a new connection 




// -------------------------------------------------------------------
// 			2. RUNNING LOOP
// -------------------------------------------------------------------
    
        while(connfd)
	{ //while connection accepted

		// waiting for a msg
		reading_size = mq_receive(queue_versEcriture, (const char *) &msg_versEcriture, sizeof(MSG_versEcriture), NULL);
		
		if(reading_size == -1)
		{
			perror("[EcritureWindows] Failed to receive msg from BAL_versEcriture:");
		}
		else
		{
			// Reading the msg
			int type = msg_versEcriture.typeMessage;
			int msgValue = msg_versEcriture.message;
			time_t hour = msg_versEcriture.heure;
			int batch = msg_versEcriture.numLot;
			int box = msg_versEcriture.cartonEnCours;

			// Convert data into strings, in order to make a unique string to send
			// Decimals number of each attributes is fixed
			char sType[2];
			parseStr(sType,1,type);		
			char sMsg[4];
			parseStr(sMsg,3,msgValue);
			char sBatch[6];
			parseStr(sBatch,5,batch);
			char sBox[5];
			parseStr(sBox,4,box);

			char msgSocket[BUFFER_SIZE]; // the msg which will be sent to the Windows application
			strcpy(msgSocket,sType);
			strcat(msgSocket,sMsg);
			strcat(msgSocket,sBatch);
			strcat(msgSocket,sBox);
			strcat(msgSocket,ctime(&hour));

			// Send the msg
			write(connfd,msgSocket,strlen(msgSocket));
			printf("Message sent: %s\n", msgSocket);

			// if End of application requested, quit
			if(type == CLOSE_APPLI)
			{
				break;
			}
		}

        }

        close(connfd);

	// Clearing
	mq_close(queue_versEcriture);

	// exit
	pthread_exit(0);


} //end thread


